<template>
  <div class="news-management-wrapper">
    <div class="dashboard-container">
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <div class="logo">
        <h2>管理后台</h2>
      </div>

      <nav class="nav-menu">
        <div class="menu-item" @click="navigateTo('/dashboard')">
          <i class="icon">📊</i>
          <span>仪表盘</span>
        </div>
        <div class="menu-item" @click="navigateTo('/user-audit')">
          <i class="icon">👥</i>
          <span>用户审核</span>
        </div>
        <div class="menu-item" @click="navigateTo('/user-management')">
          <i class="icon">👤</i>
          <span>用户管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/team-management')">
          <i class="icon">⚡</i>
          <span>队伍管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/homepage-editor')">
          <i class="icon">🏠</i>
          <span>主页编辑</span>
        </div>
        <div class="menu-item" @click="navigateTo('/system-notifications')">
          <i class="icon">📢</i>
          <span>系统通知</span>
        </div>
        <div class="menu-item active">
          <i class="icon">📰</i>
          <span>新闻管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/event-management')">
          <i class="icon">🏆</i>
          <span>赛事管理</span>
        </div>
      </nav>

      <div class="user-info">
        <div class="user-avatar">👤</div>
        <div class="user-details">
          <div class="user-name">{{ adminName }}</div>
          <div class="user-role">账号</div>
        </div>
        <button class="logout-btn" @click="handleLogout">
          退出登录
        </button>
      </div>
    </aside>

    <!-- 主要内容区域 -->
    <main class="content">
      <div class="page-header">
        <h2>新闻管理</h2>
        <div class="header-actions">
          <button class="create-btn" @click="goToPublish">发布新闻</button>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="filter-section">
        <div class="filter-item">
          <label>状态筛选：</label>
          <select v-model="filterStatus" @change="handleFilterChange">
            <option value="">全部</option>
            <option value="1">已发布</option>
            <option value="0">草稿</option>
          </select>
          <div class="filter-item" >
          <button class="refresh-btn" @click="refreshNews">
            <i class="icon">🔄</i>
            刷新
          </button>
        </div>
        </div>

      </div>

      <!-- 新闻列表 -->
      <div class="notifications-list">
        <div v-if="loading" class="loading">
          加载中...
        </div>

        <div v-else-if="newsList.length === 0" class="empty-state">
          <div class="empty-icon">📰</div>
          <p>暂无新闻</p>
        </div>

        <div v-else class="notifications-cards">
          <div 
            v-for="news in newsList" 
            :key="news.id" 
            class="notification-card"
          >
            <div class="notification-main">
              <div class="notification-info">
                <div class="notification-header">
                  <h3 class="notification-title">
                    {{ news.title }}
                  </h3>
                  <div class="notification-meta">
                    <span class="publish-time">{{ formatDate(news.publishTime || news.createTime) }}</span>
                    <span class="view-count">👁 {{ news.viewCount || 0 }}</span>
                    <span class="status" :class="news.status === 1 ? 'published' : 'draft'">
                      {{ news.status === 1 ? '已发布' : '草稿' }}
                    </span>
                  </div>
                </div>

                <div class="notification-summary">
                  {{ news.summary || (news.content ? news.content.replace(/<[^>]*>/g, '').substring(0, 50) + '...' : '无摘要') }}
                </div>
              </div>

              <div class="notification-actions">
                <button class="view-btn" @click="viewNews(news)">查看</button>
                <button class="edit-btn" @click="editNews(news)">编辑</button>
                <button class="delete-btn" @click="deleteNews(news)">删除</button>
              </div>
            </div>
          </div>
        </div>
      </div>

        <!-- 分页 -->
        <div class="pagination" v-if="totalPages > 1">
          <button 
            class="page-btn" 
            :disabled="currentPage === 1" 
            @click="changePage(currentPage - 1)"
          >
            上一页
          </button>
          <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
          <button 
            class="page-btn" 
            :disabled="currentPage === totalPages" 
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </main>
    </div>

    <!-- 查看新闻弹窗 -->
    <div v-if="showViewModal" class="modal-overlay" @click="closeViewModal">
      <div class="view-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ viewingNews?.title }}</h3>
          <button class="close-btn" @click="closeViewModal">×</button>
        </div>
        <div class="modal-content">
          <div v-if="viewingNews?.loading" class="loading-state">
            <div class="loading-spinner">加载中...</div>
          </div>
          <div v-else>
            <div class="notification-meta">
              <span>发布时间：{{ formatDate(viewingNews?.publishTime) }}</span>
              <span>浏览次数：{{ viewingNews?.viewCount }}</span>
              <!-- <span v-if="viewingNews?.publisherName">发布者：{{ viewingNews.publisherName }}</span> -->
            </div>
            <div class="notification-content" v-html="viewingNews?.content"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="delete-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-content">
          <p>确定要删除新闻 "{{ deleteTarget?.title }}" 吗？</p>
          <p class="warning-text">此操作不可恢复！</p>
          <div class="modal-actions">
            <button class="cancel-btn" @click="closeDeleteModal">取消</button>
            <button class="confirm-btn" @click="confirmDelete" :disabled="processing">
              {{ processing ? '删除中...' : '确认删除' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="showMessage" class="message-toast" :class="messageType">
      {{ messageText }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import {
  getNewsListService,
  getNewsDetailService,
  deleteNewsService
} from '@/api/admin.js'

const router = useRouter()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 管理员姓名
const adminName = computed(() => {
  return adminStore.getAdminName()
})

// 数据状态
const loading = ref(false)
const processing = ref(false)
const newsList = ref([])
const currentPage = ref(1)
const totalPages = ref(1)
const pageSize = 10
const filterStatus = ref('')

// 弹窗状态
const showViewModal = ref(false)
const showDeleteModal = ref(false)
const deleteTarget = ref(null)
const viewingNews = ref(null)

// 消息提示
const showMessage = ref(false)
const messageText = ref('')
const messageType = ref('success')

// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 退出登录
const handleLogout = () => {
  tokenStore.removeToken()
  adminStore.clearAdminInfo()
  router.push('/login')
}

// 跳转到发布新闻页面
const goToPublish = () => {
  router.push('/publish-news')
}

// 显示消息
const showMessageToast = (text, type = 'success') => {
  messageText.value = text
  messageType.value = type
  showMessage.value = true
  setTimeout(() => {
    showMessage.value = false
  }, 3000)
}

// 获取分类标签
const getCategoryLabel = (category) => {
  const labels = {
    competition: '竞赛',
    academic: '学术',
    campus: '校园',
    achievement: '成果'
  }
  return labels[category] || '竞赛'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 加载新闻列表
const loadNewsList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize
    }

    // 添加状态筛选
    if (filterStatus.value !== '') {
      params.status = filterStatus.value
    }

    const result = await getNewsListService(params)
    if (result.code === 200) {
      newsList.value = result.data.list || []
      totalPages.value = Math.ceil((result.data.total || 0) / pageSize)
    } else {
      showMessageToast(result.message || '加载新闻列表失败', 'error')
    }
  } catch (error) {
    console.error('加载新闻列表失败:', error)
    showMessageToast('加载新闻列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 筛选状态变化
const handleFilterChange = () => {
  currentPage.value = 1
  loadNewsList()
}

// 刷新新闻列表
const refreshNews = () => {
  currentPage.value = 1
  loadNewsList()
}

// 查看新闻
const viewNews = async (news) => {
  try {
    // 显示加载状态
    viewingNews.value = { ...news, loading: true }
    showViewModal.value = true

    // 调用API获取完整的新闻详情
    const result = await getNewsDetailService(news.id)
    if (result.code === 200) {
      viewingNews.value = result.data
    } else {
      showMessageToast(result.message || '获取新闻详情失败', 'error')
      closeViewModal()
    }
  } catch (error) {
    console.error('获取新闻详情失败:', error)
    showMessageToast('获取新闻详情失败，请稍后重试', 'error')
    closeViewModal()
  }
}

// 编辑新闻
const editNews = (news) => {
  router.push(`/edit-news/${news.id}`)
}

// 删除新闻
const deleteNews = (news) => {
  deleteTarget.value = news
  showDeleteModal.value = true
}

// 关闭查看弹窗
const closeViewModal = () => {
  showViewModal.value = false
  viewingNews.value = null
}

// 关闭删除弹窗
const closeDeleteModal = () => {
  showDeleteModal.value = false
  deleteTarget.value = null
}

// 确认删除
const confirmDelete = async () => {
  if (!deleteTarget.value) return

  processing.value = true
  try {
    const result = await deleteNewsService(deleteTarget.value.id)
    if (result.code === 200) {
      showMessageToast('新闻删除成功')
      closeDeleteModal()
      await loadNewsList()
    } else {
      showMessageToast(result.message || '删除失败', 'error')
    }
  } catch (error) {
    console.error('删除新闻失败:', error)
    showMessageToast('删除失败，请稍后重试', 'error')
  } finally {
    processing.value = false
  }
}

// 切换页面
const changePage = (page) => {
  currentPage.value = page
  loadNewsList()
}

// 页面初始化
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  loadNewsList()
})
</script>

<style scoped>
@import '@/assets/css/Management.css';
</style>